package input.pilot;

import logic.ships.hunter.Hunter;

import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.scene.Controller;

public class ResetRotationController extends Controller {
	
	private static final long serialVersionUID = 1L;
	private static final float DIFF = 0.01f;
	
	private Hunter hunter;
	private Quaternion targetRotation;
	
	public ResetRotationController(Hunter hunter) {
		super();
		this.hunter = hunter;
		
		Quaternion oldRot = new Quaternion(hunter.getLocalRotation());
		hunter.updateWorldVectors();
		Vector3f frontLoc = hunter.getFrontLocation();
		float yLoc = hunter.getWorldTranslation().y;
		Vector3f dir = new Vector3f(frontLoc.x, yLoc, frontLoc.z);
		hunter.lookAt(dir, Vector3f.UNIT_Y);
		targetRotation = new Quaternion(hunter.getLocalRotation());
		hunter.getLocalRotation().set(oldRot);
	}
	
	@Override
	public void update(float time) {
		if(done() || hunter.isDestroyed()) hunter.removeResetRotController();
		else hunter.getLocalRotation().slerp(targetRotation, time * 1.5f);
	}
	
	private boolean done() {
		Quaternion rot = hunter.getLocalRotation();
		if(!compare(rot.w, targetRotation.w)) return false;
		if(!compare(rot.x, targetRotation.x)) return false;
		if(!compare(rot.y, targetRotation.y)) return false;
		if(!compare(rot.z, targetRotation.z)) return false;
		return true;
	}
	
	private boolean compare(float a, float b) {
		return FastMath.abs(a - b) <= DIFF;
	}
}